//
//  Model.swift
//  Link
//
//  Created by melvyn on 2018/9/21.
//  Copyright © 2018 NEET. All rights reserved.
//

import Foundation

public protocol AnyModel {
    static var entity: String { get }
}

extension AnyModel {
    public static var entity: String {
        return "Link." + String(describing: Self.self)
    }
}

public protocol JSONConvertible: AnyModel, Codable {
    func asJSON() throws -> Any
}

extension JSONConvertible {
    public func asJSON() throws -> Any {
        return try JSONAdapter.jsonObject(from: self)
    }
}

public protocol Model: JSONConvertible, Hashable {
    associatedtype ID: Hashable & Codable
    
    typealias IDKey = KeyPath<Self, ID>
    static var idKey: IDKey { get }

    var id: ID { get }
}

extension Model {
    public static var idKey: IDKey {
        return \.id
    }
}

extension Model {
    public static func == (lhs: Self, rhs: Self) -> Bool {
        return lhs.hashValue == rhs.hashValue
    }
    
    public var hashValue: Int {
        return id.hashValue &+ Self.entity.hashValue
    }
}
